package multiconnector.broadcast;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * A {@link Broadcaster} with the functionality to send pings each x
 * milliseconds.
 */
public class PingBroadcaster extends Broadcaster {

	/**
	 * PING ACTION<br>
	 * A <i>Ping Action</i> will always send the client's mac with the Intent. <br>
	 * You can retrieve the mac by calling
	 * <code>data.getStringExtra("mac");</code>
	 */
	public static final String INTENT_ACTION_PING = INTENT_ACTION
			+ "_PING";
	private static final String LOG_TAG = PingBroadcaster.class.getName();
	private Timer mPingTimer;
	private TimerTask mPingTimerTask;

	public PingBroadcaster(Context pContext, int pPort, String pApplicationTag) throws IOException {
		super(pContext, pPort, pApplicationTag);
	}

	public static boolean isPing(Intent pIntent) {
		return isPacket(pIntent, INTENT_ACTION_PING);
	}

	public Intent getPingIntent() {
		Intent intent = new Intent(PingBroadcaster.INTENT_ACTION_PING);
		intent.putExtra("mac", getMac());
		return intent;
	}

	/**
	 * Sends a single Ping Action.
	 *
	 * @see {@link PingBroadcaster#INTENT_ACTION_PING}
	 * @see {@link PingBroadcaster#sendPing()}
	 */
	public void sendPing() {
		Log.d(LOG_TAG, "Ping send.");
		send(getPingIntent());
	}

	/**
	 * Sends every x milliseconds a Ping Action.
	 *
	 * @param pMilliseconds Intervall between each ping send.
	 * @see {@link PingBroadcaster#sendPing()}
	 * @see {@link PingBroadcaster#INTENT_ACTION_PING}
	 */
	public void sendPing(int pMilliseconds) {
		Log.d(LOG_TAG, "Ping send.");
		if (mPingTimer != null) {
			// another ping timer is running
			mPingTimerTask.cancel();
			mPingTimer.cancel();
		}

		mPingTimer = new Timer();
		mPingTimerTask = new TimerTask() {

			@Override
			public void run() {
				sendPing();
			}
		};
		mPingTimer.schedule(mPingTimerTask, 0L, pMilliseconds);
	}

}
